// ==UserScript==
// @name             New script {{name}}
// @version          {{date}}
// @description      {{date}}
// @author           alone
// @license          MIT
// @icon

// @match            {{url}}

// @grant            GM_registerMenuCommand
// @grant            GM_unregisterMenuCommand
// @grant            GM_notification
// @grant            GM_info
// @grant            GM_setValue
// @grant            GM_getValue
// @grant            GM_deleteValue
// @grant            GM_openInTab
// @grant            GM_addStyle
// @grant            GM_getResourceText

// @run-at           document-end
// @require          https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/jquery/3.5.1/jquery.min.js
// @require          https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/pako/2.0.3/pako.min.js
// @require          https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/ElementGetter.js
// @require          https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/sweetalert2.js
// @require          https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/myLib.js?timestamp=1740381556
// @resource         customCSS https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/css/myCss.css?timestamp=1740381556

// @homepageURL      https://gitee.com/zw95cn/my-scripts/blob/master/js/youhou
// @updateURL        https://gitee.com/zw95cn/my-scripts/raw/master/js/youhou/defaultTemplate.user.js
// ==/UserScript==

var updateDate = GM_info.script.version

const configIdList = [
  { group: '默认', id: 'func1', title: '功能1描述', name: '功能1名称' },
  { group: '默认', id: 'func2', title: '功能2描述', name: '功能2名称' },
  { group: '默认2', id: 'func3', title: '功能3描述', name: '功能3名称' },
]

const scriptInfo = GM_info.script,
  locHost = location.host,
  locHref = location.href,
  locHash = location.hash,
  locPath = location.pathname

// 配置对象
let t = {
  showNotice(msg) {
    GM_notification({
      text: msg,
      title: scriptInfo.name,
      image: scriptInfo.icon,
      highlight: false,
      silent: false,
      timeout: 1500,
    })
  },

  clog() {
    for (let m of arguments) {
      if (void 0 !== m) console.log(m)
    }
    console.groupEnd()
  },

  get(name, def) {
    return GM_getValue(name, def)
  },

  set(name, value) {
    GM_setValue(name, value)
  },

  setIfAbsent(name, value) {
    if (GM_getValue(name, null) == null) GM_setValue(name, value)
  },

  delete(name) {
    GM_deleteValue(name)
  },

  registerMenu(title, func) {
    return GM_registerMenuCommand(title, func)
  },

  unregisterMenu(menuID) {
    GM_unregisterMenuCommand(menuID)
  },

  open(url, options = { active: true, insert: true, setParent: true }) {
    GM_openInTab(url, options)
  },

  http(link, s = false) {
    return link.startsWith('http') ? link : (s ? 'https://' : 'http://') + link
  },

  title(a, mark = '') {
    if (a.title) a.title += '\n' + mark + decodeURIComponent(a.href)
    else a.title = mark + decodeURIComponent(a.href)
  },

  hashcode(l = location) {
    return l.hash.slice(1)
  },

  search(l = location, p = 'password') {
    let args = l.search.slice(1).split('&')
    for (let a of args) {
      if (a.includes(p + '=')) return a.replace(p + '=', '')
    }
    return ''
  },

  clean(src, str) {
    for (let s of str) {
      src = src.replace(s, '')
    }
    return src
  },

  loop(func, times) {
    let tid = setInterval(() => {
      if (times <= 0) clearInterval(tid)
      func()
      this.clog(times)
      times--
    }, 100)
  },

  confirm(title, yes, no = () => {}, deny = false) {
    let option = {
      toast: true,
      showCancelButton: true,
      position: 'center',
      title,
      confirmButtonText: '是',
      cancelButtonText: '否',
      showDenyButton: deny,
      denyButtonText: '取消',
      customClass: {
        popup: 'lh-popup',
        content: 'lh-content',
        closeButton: 'lh-close',
      },
    }
    return Swal.fire(option).then((res) => {
      if (res.isConfirmed) yes()
      else if (res.isDismissed) no()
      else if (res.isDenied) deny()
    })
  },

  rand(min, max) {
    if (arguments.length == 1) (max = min), (min = 0)
    let random = Math.random(),
      randInt = Math.floor(random * (max + 1 - min)) + min
    return randInt
  },
}
// 注册配置弹窗
function registerMenu() {
  // 如果没设置值 默认为true
  configIdList.forEach((v) => {
    t.setIfAbsent(v.id, true)
  })

  function generateHtml(config) {
    let html = `<ul class="lh-menu">`

    // 用于跟踪当前分组
    let currentGroup = null

    config.forEach((item) => {
      if (item.group !== currentGroup) {
        // 如果分组变化，添加新的分组标题
        html += `<li class="lh-item lh-item-group">
                   <span>${item.group}</span>
                 </li>`
        currentGroup = item.group
      }
      // 添加功能项
      html += `<li class="lh-item">
                 <label title="${item.title}">
                   <input type="checkbox" id="${item.id}"/>
                   <span class="checkBoxText">${item.name}</span>
                 </label>
               </li>`
    })

    html += `</ul>`
    return html
  }

  function showSettings() {
    let html = generateHtml(configIdList)

    Swal.fire({
      title: '配置',
      html,
      footer: `<div class="lh-footer">
							   <span>${formatDateVersionToDesc(updateDate)}更新</span>
							 </div>`,
      showCloseButton: true,
      showConfirmButton: true,
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: '保存',
      denyButtonText: '全部关闭',
      cancelButtonText: '恢复默认',
      customClass: {
        popup: 'lh-popup',
        content: 'lh-content',
        closeButton: 'lh-close',
      },
      didOpen: () => {
        configIdList.forEach((v) => {
          $(`#${v.id}`).prop('checked', t.get(v.id) == true, false)
        })
      },
    }).then((result) => {
      // 根据设置展示控件选中状态

      if (result.isConfirmed) {
        // 保存配置并刷新
        configIdList.forEach((v) => {
          t.set(v.id, $(`#${v.id}`).prop('checked') || false)
        })
        createAlert('已保存，稍后刷新', 'success')
        setTimeout(() => {
          window.location.reload()
        }, 3000)
      } else if (result.isDenied) {
				// 全部关闭
        configIdList.forEach((v) => {
          t.set(v.id, false)
        })
        createAlert('已全部关闭，稍后刷新', 'success')
        setTimeout(() => {
          window.location.reload()
        }, 3000)

      } else if (result.dismiss === Swal.DismissReason.cancel){
				// 重置为全部开启
        configIdList.forEach((v) => {
          t.delete(v.id)
        })
        createAlert('已重置，稍后刷新', 'success')
        setTimeout(() => {
          window.location.reload()
        }, 3000)
			}
    });
  }
  GM_addStyle(
    deGzip(
      `H4sIAAAAAAAAA5VXa5OiShL9K+7cuBH3Ro/d+GzF2IhFQcQRbVGxcWM/FFBCQfFYHgIa/d+3AB/Yj5lZCLuhqMw8eTKrMusRm3Xf82P/tPfcqB6iI6Qb0Bnkb3Sj66dPjcfONxFpgRd6+6imABOib99BgAD+bkJ8gBHSwPcQuGE9hAHaDxyQ1skcw4zoZ+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XyVnBGTk7Ef35kYxNyItWEj4cejAi0AE/2p3dGj8fYF+dv62zsrDQ+Hm4D6j85b5PJJDunTDZdb8Im3p4gnqdwF7F/WySyypvqyNast+XlH/h52S6bvz5NtjmADcLI5lgORAcDrWkavDlO7nV/VIStOXI0VITrgYqyA4feC4e4751zJ1EgHN/mTPqWxUP5M2Y0f9RLrX632yNf6Wti93wU6n8/Y//UFsPvUPAAA=`
    )
  )
  t.registerMenu('配置', showSettings)
}

let currentTrigger = null;
// 计算最佳位置并显示提示框
function showTooltip(trigger, content) {
  if (!trigger || !content) return

  currentTrigger = trigger

  // 尝试获取已有的提示框，如果没有则自动创建一个
  let tooltip = document.getElementById('dynamic-tooltip')
  if (!tooltip) {
    tooltip = document.createElement('div')
    tooltip.id = 'dynamic-tooltip'
    tooltip.className = 'tooltip-content'
    document.body.appendChild(tooltip)
  }

  // 先设置内容
  tooltip.innerHTML = content

  // 获取触发元素的位置信息
  const triggerRect = trigger.getBoundingClientRect()
  const viewportWidth = window.innerWidth
  const viewportHeight = window.innerHeight

  // 提示框尺寸（估算值）
  const tooltipPadding = 16
  const tooltipWidth = Math.max(content.length * 10, 80) // 粗略估算宽度
  const tooltipHeight = 36 // 大概高度

  let left, top, position

  // 策略：优先显示在下方，其次是上方，再调整左右以防超出屏幕

  // 1. 尝试显示在下方（bottom 方向）
  left = triggerRect.left + triggerRect.width / 2 - tooltipWidth / 2
  top = triggerRect.bottom + 10

  position = 'bottom'

  // 检查是否超出左右边界
  if (left < 10) left = 10
  if (left + tooltipWidth > viewportWidth - 10) {
    left = viewportWidth - tooltipWidth - 10
  }

  // 检查是否超出下边界（一般不会，因为我们是在下方显示）
  if (top + tooltipHeight > viewportHeight - 10) {
    // 如果下方放不下，则尝试显示在上方
    position = 'top'
    top = triggerRect.top - tooltipHeight - 10
    left = triggerRect.left + triggerRect.width / 2 - tooltipWidth / 2

    if (left < 10) left = 10
    if (left + tooltipWidth > viewportWidth - 10) {
      left = viewportWidth - tooltipWidth - 10
    }

    // 如果上方也放不下（极少数情况），则贴边显示
    if (top < 10) top = 10
  }

  // 应用位置
  tooltip.style.left = `${left}px`
  tooltip.style.top = `${top}px`

  // 显示提示框
  tooltip.classList.add('show')
}

// 隐藏提示框
function hideTooltip() {
  let tooltip = document.getElementById('dynamic-tooltip')
  tooltip.classList.remove('show');
  currentTrigger = null;
}
function bindToolTip(element) {
  if (element.getAttribute('data-tooltip')) {
      element.addEventListener('mouseenter', () => showTooltip(element, element.getAttribute('data-tooltip')));
      element.addEventListener('mouseleave',  () => hideTooltip());
  }
}


// 运行启动的功能项
function Work() {
  configIdList.forEach((v) => {
    if (t.get(v.id) == true) {
      var func = eval(v.id)
      func()
    }
  });

  // 添加自定义提示弹窗，使用：元素创建时，1使用bindToolTip方法， 2增加data-tooltip属性即可

  GM_addStyle(`
  /* 提示框基础样式 */
  .tooltip-content {
      position: fixed; /* 必须用 fixed 才能相对于视口定位 */
      background: #222;
      color: white;
      padding: 8px 16px;
      border-radius: 10px;
      font-size: 14px;
      white-space: nowrap;
      z-index: 1000;
      opacity: 0;
      visibility: hidden;
      transition: all 0.2s ease;
      box-shadow: 0 2px 8px rgba(0,0,0,0.15);
      pointer-events: none;
  }

  /* 显示状态 */
  .tooltip-content.show {
      opacity: 1;
      visibility: visible;
  }

  /* 简单箭头（可选，如需要可加上） */
  .tooltip-content::after {
      content: '';
      position: absolute;
      width: 0;
      height: 0;
      border: 6px solid transparent;
  }
  `);

  window.addEventListener('resize', hideTooltip);
}
// 个性函数部分  ================================================================================
function func1() {
  elmGetter.each("",document,(findDom)=>{

  });
  elmGetter.get('').then((findDom) => {

  });
  createAlert('成功', 'success')
}
function func2() {
  createAlert('失败', 'error')
}
function func3() {
  createAlert('警示', 'warning')
}
;(function () {
  'use strict'
  registerMenu()
  Work()
})()
